package cn.whit.blog.servlet;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.whit.blog.domain.User;
import cn.whit.blog.domain.VoteItem;
import cn.whit.blog.service.VoteItemService;
import cn.whit.blog.service.VoteService;
import cn.whit.blog.util.BeanFactory;

public class VoteItemServlet extends BaseServlet{
	
	private static final long serialVersionUID = -7593052859636319171L;
	
	VoteItemService voteItemService = (VoteItemService)BeanFactory.createObject("voteItemService");
	
	//增加投票记录 
	public String add(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//投票id
		String voteid = request.getParameter("voteid");
		//投票条目的id值
		String optionid = request.getParameter("optionid");
		System.out.println("voteid =" + voteid);
		System.out.println("optionid =" + optionid);
		
		response.setCharacterEncoding("utf-8");
		PrintWriter writer = response.getWriter();
		
		//用户是否已经登录
		User loginUser = (User) request.getSession().getAttribute("loginUser");
		if( loginUser == null) {
			//没有登录，提示先登录
			writer.write("没有登录的用户，请立即登录去!".toString());
			return null;
		}
		
		//该投票项目，是否该用户已经完成投票
		//同一个用户，一个投票项目只能投一次
		List<VoteItem> voteItemList =  voteItemService.findByUserIdAndVoteId(loginUser.getId(),voteid);
		if(voteItemList != null && voteItemList.size() > 0) {
			writer.write("您已经投票了".toString());
			return null;
		}
		
		//增加投票数据(增加投票记录数据，增加投票中的小计数据）
		VoteItem voteItem = new VoteItem();
		voteItem.setUserid(loginUser.getId());
		voteItem.setVoteid(voteid);
		voteItem.setOptionid(optionid);
		voteItemService.save(voteItem );
	
		
		//转json字符串数组返回客户端
//		Vote one = voteService.getById(id);
//		
//		JSONObject jsonStr = JSONObject.fromObject(one);
//		response.setCharacterEncoding("utf-8");
//		PrintWriter writer = response.getWriter();
//		
		writer.write("投票成功".toString());
		return null;
	}
}
